﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Text;

/// <summary>
/// This class provides features for dealing with url.
/// </summary>
public static class UrlUtility
{
	/// <summary>
	/// Url rewriting rules.
	/// </summary>
	static string[] rules = new string[]
	{
		"^/1/(.*)$",
		"^/2/(.*)$",
		"^/3/(.*)$"
	};

	/// <summary>
	/// Url rewriting destinations.
	/// </summary>
	static string[] dests = new string[]
	{
		"~/1.aspx?p=$1",
		"~/2.aspx?p=$1",
		"~/3.aspx?p=$1"
	};

	/// <summary>
	/// Rewrite url.
	/// </summary>
	/// <param name="app">Provide http-context and http-application for rewriting.</param>
	public static void RewriteUrl(HttpApplication app)
	{
		int appPathLen = app.Context.Request.ApplicationPath.Length;
		string path = app.Context.Request.Path.Substring(appPathLen);

		for(int i = 0; i < rules.Length; i++)
		{
			if(Regex.IsMatch(path, rules[i]))
			{
				app.Context.RewritePath(Regex.Replace(path, rules[i], dests[i]));
				return;
			}
		}
	}

	/// <summary>
	/// Resolve the client url for the url with '~/'.
	/// </summary>
	/// <param name="app"></param>
	public static void ResolveUrl(HttpApplication app)
	{
		int pos = app.Request.Path.IndexOf("/~/");
		if(pos != -1)
		{
			app.Context.RewritePath(app.Request.Path.Substring(pos + 1));
		}
	}

	/// <summary>
	/// Get the root path of the web application,
	/// for example, http://localhost:12345/www_root/ or http://localhost/.
	/// </summary>
	/// <returns></returns>
	public static string GetRootUrl()
	{
		StringBuilder sbUrl = new StringBuilder();
		Uri requrl = HttpContext.Current.Request.Url;

		if(requrl.Port == 80 || requrl.Port == -1)
			sbUrl.AppendFormat("http://{0}", requrl.Host);
		else
			sbUrl.AppendFormat("http://{0}:{1}", requrl.Host, requrl.Port);

		sbUrl.Append(HttpContext.Current.Request.ApplicationPath);

		if(sbUrl[sbUrl.Length - 1] != '/')
			sbUrl.Append("/");

		return sbUrl.ToString();
	}
}
